<template>
  <div class="approval-base">
    <div class="con">
      <div class="opts-button">
        <el-button
          v-if="user.Id == affairs.Creator.Id && affairs.Cancelable"
          :type="isText ? 'text' : 'primary'"
          @click="showCancel"
        >
          撤销
        </el-button>
        <el-button
          v-if="user.Id == affairs.Creator.Id && affairs.State == 'Reject'"
          :type="isText ? 'text' : 'primary'"
          @click="edit"
        >
          编辑
        </el-button>
        <el-button
          v-if="isMe && affair.Next && affair.Next.length > 0 && exe"
          :type="isText ? 'text' : 'primary'"
          @click="show"
        >{{ exe.ItemName ? exe.ItemName : "处理" }}</el-button
        >
      </div>
    </div>
    <div class="con"></div>

    <el-dialog
      class="approval-base-dialog"
      append-to-body
      v-if="isVisible"
      :visible.sync="isVisible"
      :title="affair.Flow.Name + '-' + exe.ItemName"
      width="800PX"
    >
      <div class="form">
        <div class="item" v-if="exe.ItemId">
          <div class="label">审批结论</div>
          <div class="value">
            <el-radio-group v-model="type">
              <el-radio
                :label="btn.Type"
                v-for="btn in btns"
                :key="btn.Type"
              >{{ btn.GroupName + btn.Name }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="item" v-if="type == 'Reject' && rejectOpt">
          <div class="label">{{ rejectOpt.GroupName }}步骤</div>
          <div class="value">
            <el-select
              v-model="RejectStepId"
              :placeholder="'请选择' + rejectOpt.GroupName + '步骤'"
            >
              <el-option
                v-for="step in steps"
                :key="step.Id"
                :label="step.ItemName"
                :value="step.Id"
              >
                <div
                  class="option-item"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="left">{{ step.ItemName }}</div>
                  <div class="right" style="display: flex">
                    <div
                      class="type"
                      v-if="step.Type == 'Shunt'"
                      style="display: flex"
                    >
                      <div class="staffs">
                        <span>系统</span>
                      </div>
                      <div class="state">
                        <span v-if="step.State == 'Refuse'">已拒绝</span>
                        <span v-else-if="step.State == 'Reject'">已驳回</span>
                        <span v-else-if="step.State == 'Done'">已完成</span>
                        <span v-else-if="step.State == 'Doing'">执行中</span>
                        <span
                          v-else-if="
                            step.State == 'ToDo' && step.Type == 'SubFlow'
                          "
                        >待发起</span
                        >
                      </div>
                    </div>
                    <div class="type" v-else style="display: flex">
                      <div
                        class="staffs"
                        v-if="
                          step.Step.Receivers && step.Step.Receivers.length > 1
                        "
                      >
                        <span
                        >{{ step.Step.Receivers[0].Name }}等{{
                            step.Step.Receivers.length
                          }}人</span
                        >
                      </div>
                      <div
                        class="staffs"
                        v-else-if="
                          step.Step.Receivers && step.Step.Receivers.length > 0
                        "
                      >
                        <span>{{ step.Step.Receivers[0].Name }}</span>
                      </div>
                      <div class="staffs" v-else>
                        <span>系统</span>
                      </div>
                      <div class="state">
                        <!--  [
                         <span v-if="step.State == 'Refuse'">已拒绝</span>
                         <span v-else-if="step.State == 'Reject'">已驳回</span>
                         <span v-else-if="step.State == 'Done'"
                           >已{{ tp[step.Type] }}</span
                         >
                         <span v-else-if="step.State == 'Doing'"
                           >{{ tp[step.Type] }}中</span
                         >
                         <span
                           v-else-if="
                             step.State == 'ToDo' && step.Type == 'SubFlow'
                           "
                           >待发起子流程</span
                         >
                         ] -->
                      </div>
                    </div>
                  </div>
                </div>
              </el-option>
            </el-select>
          </div>
        </div>
        <slot></slot>

        <slot name="next" v-if="type == 'Next'"></slot>
        <slot name="refuse" v-if="type == 'Refuse'"></slot>
        <slot
          name="reject"
          v-if="
            type == 'Reject' || type == 'RejectPrev' || type == 'RejectStart'
          "
        ></slot>
        <div class="item">
          <div class="label">审批意见</div>
          <div class="value">
            <el-input
              type="textarea"
              placeholder="请输入审批意见"
              v-model="template.Remark"
              show-word-limit
            >
            </el-input>
          </div>
        </div>
        <div class="item">
          <div class="label">附件</div>
          <div class="value">
            <attachment :fileArr="template.Files" :isUpload="true"></attachment>
          </div>
        </div>
      </div>
      <div class="submit">
        <el-button block type="primary" shape="circle" @click="submit">
          确定
        </el-button>
        <el-button block shape="circle" @click="cancel"> 取消 </el-button>
      </div>
    </el-dialog>
    <el-dialog
      class="approval-base-dialog"
      append-to-body
      v-if="isVisible1"
      :visible.sync="isVisible1"
      title="撤销"
      width="800PX"
    >
      <div class="form">
        <div class="item">
          <div class="label">备注</div>
          <div class="value">
            <el-input
              type="textarea"
              placeholder="请输入备注信息"
              v-model="template.Remark"
              maxlength="30"
              show-word-limit
            >
            </el-input>
          </div>
        </div>
        <div class="item">
          <div class="label">附件</div>
          <div class="value">
            <attachment :fileArr="template.Files" :isUpload="true"></attachment>
          </div>
        </div>
      </div>
      <div class="submit">
        <el-button block type="primary" shape="circle" @click="submitCancel">
          确定
        </el-button>
        <el-button block shape="circle" @click="cancel"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import attachment from "./upLoadFile"
    import {approvalOpsUrl,FlowAffairMap,approverStartSubflow} from "@/api/approval/index"

    export default {
        name: "HomeIcons",
        props: {
            affair: {
                type: Object,
                required: true,
            },
            tps: {
                type: Object,
            },
            isText: {
                type: Boolean,
                default: true,
            },
        },
        watch: {
            affair: {
                handler(newVal) {
                    this.affairs = newVal;
                    this.init();
                },
                deep: true,
            },
            tps: {
                handler(newVal) {
                    this.tp = newVal;
                },
            },
        },
        data() {
            return {
                tp: null,
                isVisible: false,
                isVisible1: false,
                template: {
                    Remark: "",
                    Files: [],
                },
                type: "",
                NextCode: "Next",
                RefuseCode: "Refuse",
                RejectCode: "Reject",
                RejectStartCode: "RejectStart",
                RejectPrevCode: "RejectPrev",
                StepId: "",
                RejectStepId: "",
                isMe: false,
                user: {},
                btnMaps: {},
                exe: null,
                rejector: {
                    Name: "",
                    Index: -1,
                    StepId: "",
                },
                rejectName: "",
                rejectOpt: null,
                rejects: [],
                rejectAllShow: false,
                steps: [],
                rejectSteps: false,
                rejectStep: null,
                user: null,
                affairs: {},
                btns:[]
            };
        },
        methods: {
            //驳回
            show() {
                if (this.type != this.RejectCode) {
                    this.template.Remark = "";
                    this.template.Files.splice(0, this.template.Files.length);
                }
                this.isVisible = true;
            },
            showCancel() {
                // this.isVisible1 = true;

                this.$confirm('是否撤销此次审核?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.submitCancel()

                }).catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: '已取消删除'
                    // });
                });
            },
            submitCancel() {
                this.$emit('cancel',this.affairs.Id,this.StepId,"Cancel",this.template,this.RejectStepId,this.submitCallbacks)
                // this.isVisible1 = false;
            },
            cancel() {
                this.isVisible = false;
                this.isVisible1 = false;
            },
            //发起子流程
            initiate() {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                approverStartSubflow(affId, stepId, this.exe.ItemId).then((res) => {
                    let flow = res.data.Flow;
                    let url = res.data.Url;
                    let item = res.data.Item;
                    this.$router.push({
                        path: url.Add,
                        name: url.Add,
                        params: {
                            app: flow,
                            superId: this.affairs.Id,
                            superStepId: this.StepId,
                        },
                    });
                });
            },
            submit() {
                if (this.type == "Reject" && !this.RejectStepId) {
                    this.$message.error("请选择" + this.rejectOpt.GroupName + "步骤");
                    return;
                }
                if (this.exe.ItemId && !this.type) {
                    this.$message.error("请选择审批结论");
                    return;
                }
                this.$emit(
                    "submit",
                    this.affairs.Id,
                    this.StepId,
                    this.exe.ItemId ? this.type : "Next",
                    this.template,
                    this.RejectStepId,
                    this.submitCallbacks
                );
            },
            submitCallbacks(suc) {
                if (suc) {
                    this.isVisible = false;
                    this.isVisible1 = false
                }
            },
            submitAgree(val) {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                if (val) {
                    approverApprovalSubmit(affId, stepId, this.template, val).then(
                        (res) => {
                            if (res.state > 0) {
                                this.submitCallback(res.data);
                            } else {
                                this.$message.error(res.msg);
                            }
                        }
                    );
                }
            },
            submitRefuse(val) {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                if (val) {
                    approverRefuseSubmit(affId, stepId, this.template).then((res) => {
                        if (res.state > 0) {
                            this.submitCallback(res.data);
                        } else {
                            this.$message.error(res.msg);
                        }
                    });
                }
            },
            submitReject(val) {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                if (val) {
                    approverRejectSubmit(
                        affId,
                        stepId,
                        this.rejectStep.Id,
                        this.template
                    ).then((res) => {
                        if (res.state > 0) {
                            this.submitCallback(res.data);
                        } else {
                            this.$message.error(res.msg);
                        }
                    });
                }
            },
            submitRejectStart(val) {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                if (val) {
                    approverRejectStartSubmit(affId, stepId, this.template).then((res) => {
                        if (res.state > 0) {
                            this.submitCallback(res.data);
                        } else {
                            this.$message.error(res.msg);
                        }
                    });
                }
            },
            submitRejectPrev(val) {
                var affId = this.affairs.Id;
                var stepId = this.StepId;
                if (val) {
                    approverRejectPrevSubmit(affId, stepId, this.template).then((res) => {
                        if (res.state > 0) {
                            this.submitCallback(res.data);
                        } else {
                            this.$message.error(res.msg);
                        }
                    });
                }
            },
            submitCallback(data) {
                if (data.Next == null) {
                    data.Next = [];
                }
                this.affairs.Next.splice(0, this.affairs.Next.length, ...data.Next);
                this.affairs.Steps.splice(0, this.affairs.Steps.length, ...data.Steps);
                this.init();
                this.isVisible = false;
                this.$emit("refresh", this.affairs);
            },
            edit() {
                this.$emit("toEdit", this.affairs);
            },
            getFlowAffairMap() {
                FlowAffairMap().then((res) => {
                    this.tp = res.data;
                });
            },
            getSteps(id, steps) {
                let s1 = [];
                let mp = [];
                for (let item of steps) {
                    if (!mp[item.ItemId]) {
                        mp[item.ItemId] = item;
                        s1.push(item);
                    }
                }
                var step = steps[steps.length - 1];
                if (id == step.Id) {
                    return s1;
                } else if (step.Type == "Shunt") {
                    var shunts = step.Step.Shunts;
                    for (var shunt of shunts) {
                        var ss = this.getSteps(id, shunt.Steps);
                        if (ss) {
                            return ss;
                        }
                    }
                }
                return null;
            },
            initSteps() {
                var exe = this.exe;
                this.steps.splice(0,this.steps.length)
                if (exe) {
                    var steps = this.getSteps(exe.StepId, this.affairs.Steps);
                    var s = JSON.parse(JSON.stringify(steps))
                    let ss =[]
                    let map ={}
                    for(let step of s){
                        if(step.ItemId== exe.ItemId){
                            break;
                        }
                        if(!map[step.ItemId]){
                            ss.push(step)
                            map[step.ItemId]=step
                        }else{
                            break
                        }
                    }
                    if(steps){
                        this.steps.push(...ss)
                    }
                    console.log("steps", steps);
                }
            },
            init() {
                if (this.affairs.State == "Reject") {
                    this.isMe = this.user.Id == this.affairs.Creator.Id;
                } else {
                    this.btns.splice(0,this.btns.length)
                    this.isMe = false;
                    this.btnMaps = {};
                    this.rejects.splice(0, this.rejects.length);
                    this.rejectOptCount = 0;
                    this.rejectName = "";
                    this.rejectOpt = null;
                    if (this.affairs.Next) {
                        for (let exe of this.affairs.Next) {
                            if (!exe) {
                                continue;
                            }
                            for (let s of exe.Staffs) {
                                if (s == this.user.Id) {
                                    this.isMe = true;
                                    this.StepId = exe.StepId;
                                    this.exe = exe;
                                    this.initSteps();
                                    if (exe.Buttons) {
                                        for (let btn of exe.Buttons) {
                                            this.$set(this.btnMaps, btn.Type, btn);
                                            if(btn.Group=='Reject'){
                                                this.rejectOptCount ++
                                                this.rejectName = btn.GroupName;
                                                this.rejectOpt = btn;
                                                console.log(this.rejectOpt)
                                                btn.name=btn.Name
                                                btn.value=btn.Type
                                                this.rejects.push(btn)
                                            }
                                        }
                                        let isRoot = this.steps[0].Id == this.affair.Steps[0].Id
                                        console.log('btnMaps',this.btnMaps)
                                        if(this.btnMaps.Next){
                                            this.btns.push(this.btnMaps.Next)
                                        }
                                        if(this.btnMaps.Initiate){
                                            this.btns.push(this.btnMaps.Initiate)
                                        }
                                        if(this.btnMaps.Refuse){
                                            this.btns.push(this.btnMaps.Refuse)
                                        }
                                        //根流程节点，非分流节点
                                        if(isRoot){
                                            if(this.steps.length>1){
                                                if(this.btnMaps.RejectStart){
                                                    this.btns.push(this.btnMaps.RejectStart)
                                                }
                                                if(this.btnMaps.RejectPrev){
                                                    this.btns.push(this.btnMaps.RejectPrev)
                                                }
                                                if(this.btnMaps.Reject){
                                                    this.btns.push(this.btnMaps.Reject)
                                                }
                                            }else if(this.steps.length==1){
                                                if(this.btnMaps.RejectStart){
                                                    this.btns.push(this.btnMaps.RejectStart)
                                                }else if(this.btnMaps.RejectPrev){
                                                    this.btns.push(this.btnMaps.RejectPrev)
                                                }else if(this.btnMaps.Reject){
                                                    this.btns.push(this.btnMaps.Reject)
                                                }
                                            }
                                        }else{
                                            if(this.steps.length>1){
                                                if(this.btnMaps.RejectPrev){
                                                    this.btns.push(this.btnMaps.RejectPrev)
                                                }
                                                if(this.btnMaps.Reject){
                                                    this.btns.push(this.btnMaps.Reject)
                                                }
                                            }else if(this.steps.length==1){
                                                if(this.btnMaps.RejectPrev){
                                                    this.btns.push(this.btnMaps.RejectPrev)
                                                }else if(this.btnMaps.Reject){
                                                    this.btns.push(this.btnMaps.Reject)
                                                }
                                            }
                                        }
                                    }
                                    return;
                                }
                            }
                        }
                    }
                }
            },
        },
        created() {
            this.user = {Id:this.$store.getters.userInfo.user.id}
            this.affairs = this.affair;
            this.init();
            this.tp = this.tps;
            if (!this.tps) {
                this.getFlowAffairMap();
            }
        },
        computed: {},
        components: {
            attachment,
        },
    };
</script>
<style lang="scss" scoped>
  @import "@/styles/variables.scss";
  .approval-base {
    display: inline-block;
    // margin-right: @block-img-img-x;
    margin-left: $block-img-img-x;
    .form {
      .item ::v-deep .approval_item {
        display: flex;
        padding-bottom: $block-space-y;
        .label {
          width: 100px;
          text-align: right;
          margin-right: $block-space-x;
        }
        .value {
          width: 100%;
        }
        .el-select {
          width: 100%;
        }
      }
    }
    .submit {
      display: flex;
      justify-content: center;
    }
  }
  body ::v-deep .el-select-dropdown {
    color: red;
    .el-select-dropdown__item {
      .option-item {
        display: flex;
        .right {
          display: flex;
          .type {
            display: flex;
          }
        }
      }
    }
  }

  .approval-base-dialog{
    .form{
      .item, ::v-deep .approval_item{
        display: flex;
        padding-bottom: $block-space-y;
        .label{
          width: 100PX;
          text-align: right;
          margin-right: $block-space-x;
        }
        .value{
          width:100%
        }
        .el-select{
          width:100%;
        }
      }
    }
    .submit{
      display: flex;
      justify-content: flex-end;
    }
  }

</style>
